#!/bin/bash
<% if lsb %>
### BEGIN INIT INFO
# Provides:          iyyov
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Should-Start:      $named
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: Iyyov jruby monitor
# Description:       Iyyov jruby monitoring and job control daemon
### END INIT INFO

. /lib/lsb/init-functions
<% else %>
# iyyov    Startup script for Iyyov monitoring daemon
#
# chkconfig: 2345 88 12
# description: Iyyov monitoring and job control daemon
# processname: iyyov
# config: /opt/var/iyyov/jobs.rb

. /etc/rc.d/init.d/functions
<% end %>

# Gem home directory
# Set to match system "jgem environment path"
gem_home="<%= local_root %>/lib/jruby/gems"

# (Exact) Gem version of iyyov to run
version="<%= iyyov_version %>"

# User to run the daemon as (should own rundir)
user="<%= run_user %>"

# Running directory (for jobs.rb config, log, and pid file)
rundir="<%= run_dir %>/iyyov"

# Add PATH to jruby if non-standard
export PATH=$PATH:<%= local_root %>/bin

prog="iyyov"
daemon="${gem_home}/gems/iyyov-${version}-java/init/${prog}"
config="${rundir}/jobs.rb"
pidfile="${rundir}/${prog}.pid"

RETVAL=0

start() {
    [ -x "$daemon" ] || exit 5
    [ -f "$config" ] || exit 6
    [ -d "$rundir" ] || exit 7

<% if lsb %>
    log_daemon_msg "Starting Iyyov Daemon" "iyyov"
    start-stop-daemon --start -d $rundir -c $user --exec $daemon -- $config
    RETVAL=$?
    log_end_msg $RETVAL
<% else %>
    echo -n $"Starting $prog: "
    runuser -c "cd $rundir && $daemon $config" $user
    RETVAL=$?
    [ $RETVAL -eq 0 ] && success $"$prog startup" || failure $"$prog startup"
    echo
<% end %>
}

status() {
    if [ -f "$pidfile" ]; then
        echo "Status $prog: running pid $(<$pidfile)"
    else
        echo "Status $prog: not running"
    fi
}

reload() {
    if [ -e "$pidfile" ]; then
        touch $config
    fi
}

stop() {
<% if lsb %>
    log_daemon_msg "Stopping iyyov daemon" "iyyov"
    start-stop-daemon --stop --quiet --oknodo --pidfile $pidfile
    RETVAL=$?
    log_end_msg $RETVAL
<% else %>
    echo -n $"Shutting down $prog: "
    killproc -p $pidfile $prog
    RETVAL=$?
    [ $RETVAL -eq 0 ] && success || failure
    echo
    return $RETVAL
<% end %>
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
        status
        ;;
    reload)
        reload
        ;;
    restart)
        stop
        start
        RETVAL=$?
        ;;
    condrestart)
        [ -e $pidfile ] && restart
        RETVAL=$?
        ;;
    *)
        echo $"Usage: $0 {start|stop|status|reload|restart|condrestart}"
        RETVAL=1
esac

exit $RETVAL
